home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 14779 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.5 KB  |  44 lines

  1. Path: news.compuserve.com!newsmaster
  2. From: Philippe Verdy <100105.3120@compuserve.com>
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: 2 D arrays in C++ constructors
  5. Date: 1 Apr 1996 23:42:04 GMT
  6. Organization: CompuServe Incorporated
  7. Message-ID: <4jppkc$lhj@dub-news-svc-6.compuserve.com>
  8. NNTP-Posting-Host: ad15-078.compuserve.com
  9.  
  10. rsuri@csugrad.cs.vt.edu (Raj Suri) s'Θcrit :
  11. > Ok,
  12. > I wrote a c++ class that used an array of integers.  However, I didn't know the
  13. > size of the array until the constructor was called.  So I did this:
  14. > class ... {
  15. >  private:
  16. >   int* ptr;
  17. > And then in the constructor, I had this code:
  18. >   ptr = new int[10];
  19. > This works fine.  However, now I need to use a two dimensional array in 
  20. > which I don't know the dimensions until the constructor is called.  I can't
  21. > figure out how to declare ptr and allocate space to it such that I could do the
  22. > following statement:
  23. > ptr[2][3] = 4;
  24. > Any help.. Thanks in advance.
  25. > -Raj
  26. If you don't know the first dimensions, there will be no way
  27. to declare a pointer for a 2D array.
  28. However, you can build up a class which internally allocates
  29. a 1D array and an appropriate constructor which allocates the
  30. product of the dimensions. Then associate is to your pointer
  31. type, by registrating this pointer with the actual dimensions
  32. used, and then add an array index operator[] to do the
  33. first indirection (it will return a 1D array pointer, i.e. a
  34. simple pointer, on which the standard 1D [] index operator can
  35. apply...)
  36.